package lib

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
)

func Ip2Address(ip string) string {
	_url := "https://ip.taobao.com/outGetIpInfo"
	param := url.Values{}
	param.Add("ip", ip)
	param.Add("accessKey", "alibaba-inc")
	_response, _err := http.PostForm(_url, param)
	// url fail
	if _err != nil {
		return "ip解析失败 -1"
	}
	defer _response.Body.Close()

	_res, _err := ioutil.ReadAll(_response.Body)
	// 数据解析失败
	if _err != nil {
		return "ip解析失败 -2"
	}

	_data := make(map[string]any)
	_err = Loads(_res, &_data)
	// 转结构失败
	if _err != nil {
		return "ip解析失败 -3"
	}

	_queryMsg := _data["msg"].(string)
	// 查询失败
	if _queryMsg != "query success" {
		return _queryMsg
	}

	_mapData, _ := _data["data"].(map[string]any)
	_address := fmt.Sprintf(
		"%s-%s-%s %s",
		_mapData["country"].(string),
		_mapData["region"].(string),
		_mapData["city"].(string),
		_mapData["isp"].(string),
	)
	return _address
}
